<?php

namespace MoChat\ClientNew\Action;

use Carbon\Carbon;
use Hyperf\DbConnection\Db;
use MoChat\ClientNew\Model\ClientFollowRecord;
use MoChat\ClientNew\Model\ClientNew;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;

use Qbhy\HyperfAuth\AuthManager;

/**
 * @Controller
 */
class Detail extends AbstractAction
{
    use ValidateSceneTrait;

    protected $auth;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class)
     * })
     * @RequestMapping(path="/client-new/detail", methods="get")
     */
    public function handle(): array
    {
        $params = $this->request->all();
        $user =user();
        if (empty($user)) {
            throw new CommonException(ErrorCode::AUTH_UNAUTHORIZED, '登入异常请重新登入');
        }
        $params['clientId'] = (int)$params['clientId'];
        $data=ClientNew::query()->where('id',$params['clientId'])->first()->toArray();

        $province = Db::table('district')->where('id', $data['province'])->value('name');
        $city = Db::table('district')->where('id', $data['city'])->value('name');
        $district = Db::table('district')->where('id', $data['district'])->value('name');
        $data['preAddress'] = $province . $city . $district;

//        $data['contact_ids']= Db::table('client_contact_pivot')->where('client_id', (int)$params['clientId'])->pluck('contact_id')->toArray();
//        $data['contact_array']=Db::table('work_contact')
//            ->whereIn('id',$data['contact_ids'])
//            ->select(['name', 'id'])
//            ->get()->toArray();
        $init=[
            'id'=>0,
            'name'=>$data['enterpriseName'],
            'phone'=>$data['mobile'],
        ];

        $data['contact_array']= Db::table('client_phone')
            ->where('client_id',$params['clientId'])
            ->select(['name', 'id','phone'])
            ->get()->toArray();
        //在$data['contact_array'] 中第一个位置添加元素
        array_unshift($data['contact_array'],$init);
        return $data;
    }
}
